using Microsoft.Extensions.Logging;
using Quartz;
using Vin.Extension.NLog;
using Vin.Extension.Redis.Cache;
using Vin.Tool.AspNetCore.Singleton;

namespace Vin.Extension.Framework.Quartz.Jobs;

public abstract class VinBaseJob : IJob
{
    protected ILogger Logger => VinApp.GetLogger(this.GetType());
    protected virtual string LoggerName => this.GetType().Name;

    #region Redis

    public RedisCache RedisCache => GetRedisCache();

    public RedisCache GetRedisCache(int db = 0)
    {
        return RedisCacheManager.GetRedisCache(db);
    }

    #endregion

    public async Task<bool> CheckJobIdSame(IJobExecutionContext context, string redisJobMapKey, string businessId)
    {
        var jobId = context.JobDetail.Key.Name;
        // 判断活动的任务是否与当前任务一致
        var oldJobId = await RedisCache.GetHashCacheAsync<string>(redisJobMapKey, businessId);
        if (oldJobId != jobId)
        {
            Logger.Warn(LoggerName, "任务Id不一致");
            return false;
        }
        
        // 判断是否已经被其他进程执行
        if (!await RedisCache.RemoveHashCacheAsync(redisJobMapKey, businessId))
        {
            Logger.Warn(LoggerName, "任务不存在，可能已经被其他进程执行了");
            return false;
        }

        return true;
    }


    public VinBaseJob()
    {
        VinApp.Inject(this);
    }

    public abstract Task Execute(IJobExecutionContext context);
}